package refund

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import com.trjcn.wxpay.model.request.WXPayRefundRequest
import com.trjcn.wxpay.utils.RandomUtil
import enums.PayChannelEnum
import org.apache.commons.lang3.StringUtils
import org.springframework.beans.factory.InitializingBean
import org.springframework.stereotype.Service

@Service
class WXPayRefundAction extends BaseRefundAction with InitializingBean{

  override def getPayChannel: Integer = PayChannelEnum.WX_PAY.getId

  @throws[Exception]
  override def refund[T <: RefundOrderReqDTO, R >: RefundOrderRespDTO](req: T): R = {
    val wxPayRefundRequest = new WXPayRefundRequest
    wxPayRefundRequest.setOutTradeNo(req.getOriPayOrderNo)
    wxPayRefundRequest.setOutRefundNo(req.getPayRefundOrderNo)
    wxPayRefundRequest.setTotalFee(req.getPayAmount)
    wxPayRefundRequest.setRefundFee(req.getRefundAmount)
    wxPayRefundRequest.setAppid(wxPayProperties.getAppId)
    wxPayRefundRequest.setMchId(wxPayProperties.getMchId)
    wxPayRefundRequest.setNotifyUrl(wxPayProperties.getRefundNotifyURL)
    wxPayRefundRequest.setNonceStr(RandomUtil.getRandomStr)
    log.info("wxpay refund request params : {} ", JSON.toJSONString(wxPayRefundRequest, SerializerFeature.PrettyFormat))
    val refundResponse = wxPayService.refund(wxPayRefundRequest, wxPayProperties.getCertPath)
    log.info("wxpay refund response result : {}", JSON.toJSONString(refundResponse, SerializerFeature.PrettyFormat))
    val resp = new RefundOrderRespDTO
    //BeanUtils.copyProperties(req, resp);
    resp.setPayChannel(req.getPayChannel)
    resp.setAmount(req.getRefundAmount)
    resp.setPayOrderNo(req.getPayRefundOrderNo)
    resp.setBizOrderNo(req.getBizRefundOrderNo)
    resp.setBizCode(if (StringUtils.isNotBlank(req.getBizCode)) req.getBizCode else PayEnum.BizCodeEnum.TRJ_APP_2019.getCode)
    resp.setUserId(req.getUserId)
    if (!(refundResponse.getResultCode == wxPayProperties.WX_PAY_SUCCESS)) {
      resp.setOrderStatusCode(ThirdSystemErrorEnum.getErrorEnum(refundResponse.getErrCode).getCode)
      resp.setOrderStatusMessage(ThirdSystemErrorEnum.getErrorEnum(refundResponse.getErrCode).getMessage)
    }
    else {
      resp.setOrderStatusCode(PayEnum.RefundTradeStatusEnum.getByThirdCode(refundResponse.getResultCode, req.getPayChannel).getCode)
      resp.setOrderStatusMessage(PayEnum.RefundTradeStatusEnum.getByThirdCode(refundResponse.getResultCode, req.getPayChannel).getDesc)
    }
    resp
  }

  override def afterPropertiesSet(): Unit = ActionFactory.setRefundAction(getPayChannel, this)
}
